<template>
  <div class="custom-data-panel">
    <!-- <div class="row">
      <div class="row-sub-title" style="flex: 1;">字段</div>
      <div class="row-sub-title" style="flex: 3;">映射</div>
      <div class="row-sub-title" style="flex: 1; text-align: right;">状态</div>
    </div>
    <div class="row" v-if="keywordArray.length > 0">
      <div class="row-sub-title" style="flex: 1;">S</div>
      <Select style="flex: 3;" :value="dataS" @change="value => updateDataS(value)">

        <SelectOption v-for="item in keywordArray" :key="item" :value="item">
          {{ item }}
        </SelectOption>
        <SelectOption value="无">无</SelectOption>
      </Select>

      <div class="row-sub-title" style="flex: 1; text-align: right;"><i class="appIcon-iconfont appIcon-duihao"></i></div>
    </div>
    <div class="row" v-if="keywordArray.length > 0">
      <div class="row-sub-title" style="flex: 1;">X</div>
      <Select style="flex: 3;" :value="dataX" @change="value => updateDataX(value)">
        <SelectOption v-for="item in keywordArray" :key="item" :value="item">
          {{ item }}
        </SelectOption>
      </Select>
      <div class="row-sub-title" style="flex: 1; text-align: right;"><i class="appIcon-iconfont appIcon-duihao"></i></div>
    </div>
    <div class="row" v-if="keywordArray.length > 0">
      <div class="row-sub-title" style="flex: 1;">Y</div>
      <Select style="flex: 3;" :value="dataY" @change="value => updateDataY(value)">
        <SelectOption v-for="item in keywordArray" :key="item" :value="item">
          {{ item }}
        </SelectOption>
      </Select>
      <div class="row-sub-title" style="flex: 1; text-align: right;"><i class="appIcon-iconfont appIcon-duihao"></i></div>
    </div> -->
    <div class="row">
      <div class="row-sub-title" style="flex: 2;">数据源类型</div>
      <Select style="flex: 4;" :value="dataType" @change="value => updateDataType(value)">
        <SelectOption value="json">静态数据</SelectOption>
        <!-- <SelectOption value="api">API</SelectOption>
        <SelectOption value="mysql">MySQL数据库</SelectOption> -->
      </Select>
    </div>
    <div id="json-editor" class="editor-container"></div>

  </div>
</template>

<script lang="ts">
import { computed, defineComponent, ref, onMounted, watch, onUnmounted } from 'vue'
import useHistorySnapshot from '@/hooks/useHistorySnapshot'
import { storeToRefs } from 'pinia'
import { useMainStore, useSlidesStore } from '@/store'
import { ChartData, PPTChartElement } from '@/types/slides'

import * as monaco from 'monaco-editor'

export default defineComponent({
  name: 'custom-data-panel',
  setup() {
    const dataType = ref('静态数据')
    const dataS = ref('type')
    const dataX = ref('type')
    const dataY = ref('sales')
    const mainStore = useMainStore()
    const slidesStore = useSlidesStore()
    const { handleElement, handleElementId } = storeToRefs(mainStore)
    const { theme, currentSlide } = storeToRefs(slidesStore)
    const { addHistorySnapshot } = useHistorySnapshot()
    const chartname = ref<string>()
    let jsEditor: any = null
    let antvData: any = ref(null)
    const keywordArray: any = ref([])
    const antvDataType = ref()

    const options = {
      fontFamily:
        'Monoid,Droid Sans Mono,"Microsoft YaHei",Helvetia,"lucida Grande",Verdana,Arial',
      fontSize: 12,
      theme: "vs-dark",
      automaticLayout: true,
      fixedOverflowWidgets: true,
      "formatOnPaste": true,
      "formatOnType": true,
      language: "json",
    }


    onMounted(() => {
      initCodeEditor();
    })

    const initCodeEditor = () => {
      jsEditor = monaco.editor.create(document.getElementById('json-editor') as HTMLElement, {
        value: antvData.value,
        ...options
      })
      setTimeout(() => {
        jsEditor.getAction('editor.action.formatDocument').run();
      }, 100)

      jsEditor.onDidChangeModelContent((val: any) => {
        const newVal = jsEditor.getValue()
        jsEditor.getAction('editor.action.formatDocument').run();
        getKeyWords(JSON.parse(newVal))
        antvData.value = newVal
        updateSlide({ data: newVal, s: 'name', x: 'type', y: 'sales' })
      })
    }
    //获取全部关键字
    const getKeyWords = (val: any) => {
      let keywordsSet = new Set()

      val.map((item: any) => {
        Object.keys(item as Object).map((key) => {
          keywordsSet.add(key);
        })
      })
      // console.log("getKeyWordsgetKeyWordsgetKeyWords", Array.from(keywordsSet))
      // console.log("getKeyWordsgetKeyWordsgetKeyWords", [...keywordsSet])

      keywordArray.value = [...keywordsSet]
      console.log("getKeyWordsgetKeyWordsgetKeyWords", keywordArray.value)
    }

    // 设置数据类型
    const updateDataType = (type: 'json' | 'api' | 'mysql') => {
      console.log("切换数据类型：", type)
      dataType.value = type;
      updateSlide({ 'antvData': type })
    }

    // 设置S
    const updateDataS = (s: string) => {
      console.log("切换数据类型：", s)
      dataS.value = s;
      const newVal = jsEditor.getValue()
      updateSlide({ data: newVal, s, x: dataX.value, y: dataY.value })
    }

    // 设置X
    const updateDataX = (x: string) => {
      console.log("切换数据类型：", x)
      dataX.value = x;
      const newVal = jsEditor.getValue()
      updateSlide({ data: newVal, s: dataS.value, x, y: dataY.value })
    }

    // 设置S
    const updateDataY = (y: string) => {
      console.log("切换数据类型：", y)
      dataY.value = y;
      const newVal = jsEditor.getValue()
      updateSlide({ data: newVal, s: dataS.value, x: dataX.value, y })
    }

    const updateSlide = (props: any) => {
      if(handleElement.value) {
        slidesStore.updateElement({
          id: handleElement.value?.id, props: {
            data:
            {
              type: JSON.parse(antvDataType.value),
              data: JSON.parse(props.data)
            }
          }
        })
      }
      // slidesStore.updateSlide({props})
      addHistorySnapshot()
    }

    watch(handleElement, (val: any, oldval: any) => {
      if (!handleElement.value || handleElement.value.type !== 'chart') return
      antvData.value = JSON.stringify(handleElement.value.data.data)
      antvDataType.value = JSON.stringify(handleElement.value.data.type)
      if(oldval && val.id != oldval.id) jsEditor.setValue(antvData.value)
      
      // chartname.value = handleElement.value.name || ''

    }, { deep: true, immediate: true })

    onUnmounted(() => {
      jsEditor.dispose();
    })

    return {
      dataType,
      updateDataType,
      updateDataS,
      updateDataX,
      updateDataY,
      updateSlide,
      keywordArray,
      dataS,
      dataX,
      dataY,
      getKeyWords,
      antvDataType,

    }
  },
})
</script>

<style lang="scss" scoped>
.custom-data-panel {
  height: 100%;
  display: flex;
  flex-direction: column;

  .tabs {
    display: flex;
    justify-content: space-around;
    align-items: center;
    border-bottom: 1px solid $borderColor;
    margin-bottom: 8px;
  }

  .tab {
    padding: 6px 10px 8px;
    border-bottom: 2px solid transparent;
    cursor: pointer;

    &.active {
      border-bottom: 2px solid $themeColor;
    }
  }

  .pool {
    padding: 5px 12px;
    margin: 0 -12px;
    flex: 1;
    font-size: 18px;

    @include overflow-overlay();
    @include flex-grid-layout();
  }

  .symbol-item {
    @include flex-grid-layout-children(5, 18%);

    height: 0;
    padding-bottom: 18%;
    position: relative;
    cursor: pointer;
    border: 1px solid $borderColor;

    &:hover {
      color: $themeColor;
    }

    .symbol {
      @include absolute-0();

      display: flex;
      justify-content: center;
      align-items: center;
      background-color: $leftbg;
      border-radius: 4px;
    }
  }
}

.row {
  width: 100%;
  display: flex;
  align-items: center;
  margin-bottom: 22px;
}

#json-editor {
  height: 400px;
  border: solid 1px #545455;
}

.monaco-editor {
  background-color: #181a24 !important;
}
</style>
